﻿using AutoMapper;
using DearlerPlatform.Common;
using DearlerPlatform.Core.DataBaseCommon;
using DearlerPlatform.Core.Repository;
using DearlerPlatform.Domain.Entity;
using DearlerPlatform.Service.ProductApp.Views;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DearlerPlatform.Service.ProductApp
{
    public partial class ProduceService : IProduceService
    {
        private readonly IRepository<Products> _productRepo;
        private readonly IRepository<Productphotos> _productPhotoRepo;
        private readonly IRepository<Productsaleareadiffs> _productSaleAreRepo;
        private readonly IRepository<Productsales> _productSaleRepo;
        private readonly ISqlSugarClient _db;
        private readonly IMapper _mapper;

        public ProduceService(IRepository<Products> productRepo,
            IRepository<Productphotos> productPhotoRepo,
            IRepository<Productsaleareadiffs> productSaleAreRepo,
            IRepository<Productsales> productSaleRepo,
            ISqlSugarClient db,
            IMapper mapper)
        {
            this._productRepo = productRepo;
            this._productPhotoRepo = productPhotoRepo;
            this._productSaleAreRepo = productSaleAreRepo;
            this._productSaleRepo = productSaleRepo;
            this._db = db;
            this._mapper = mapper;
        }

        public async Task<PageViewBase<List<ProductsVM>>> GetPageListAsync(QueryParameterBase query)
        {
            var resCode = await _productRepo.GetPageListAsync(query);
            var newData = _mapper.Map<List<Products>, List<ProductsVM>>(resCode.Data);
            var res = _mapper.Map<CorePageData<List<Products>>, PageViewBase<List<ProductsVM>>>(resCode);
            //取得主商品信息
            res.Data = newData;
            //取得商品图片信息
            var productPhotos = await GetProductPhotosByProductNo(res.Data.Select(m=>m.Productno).ToArray());
            //取得商品价格信息
            var productSales = await GetProductSalesByProductNo(res.Data.Select(m => m.Productno).ToArray());
            //对商品的图片及价格赋值
            res.Data.ForEach(p =>
            {
                p.ProductPhoto = productPhotos.FirstOrDefault(m => m.Productno == p.Productno);
                p.ProductSale = productSales.FirstOrDefault(m => m.Productno == p.Productno);
            });
            return res;
        }
    }
}
